package servlet;

import entity.Product;
import service.IProductService;
import service.IShoppingcarService;
import service.impl.ProductServiceImpl;
import service.impl.ShoppingcarServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "btcs", urlPatterns = {"/sub_to_car"})
public class SubToCarServlet extends HttpServlet {
    private IProductService ps = new ProductServiceImpl();
    private IShoppingcarService scs = new ShoppingcarServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String pidStr = request.getParameter("pid");
        String countStr = request.getParameter("count");

        int pid = Integer.parseInt(pidStr);
        int count = Integer.parseInt(countStr);
        Product p = ps.showDetail(pid);

        //从session中获取购物车
        HttpSession session = request.getSession();
        Map<Product, Integer> shoppingcar = (Map<Product, Integer>) session.getAttribute("sc");
        scs.countDown(shoppingcar, p, count);


//        //重定向到购物车页面
        response.sendRedirect("shopcart.jsp");
    }
}